﻿using System.Data.Entity;
using System.Data.Entity.Database;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration;
using System.ComponentModel.DataAnnotations;

namespace PMngr.Data.EF
{
    public class UnitContext : DbContext
    {
        public UnitContext()
            : base("SQLCE4.sdf")
        {
            //Configuration.LazyLoadingEnabled = false;
            #region IObjectContextAdapter
            //var contextOptions = ((IObjectContextAdapter)this).ObjectContext.ContextOptions;
            //contextOptions.ProxyCreationEnabled = false;
            //contextOptions.LazyLoadingEnabled = false;
            #endregion
            DbDatabase.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
            //DbDatabase.SetInitializer<UnitContext>(new DropCreateDatabaseIfModelChanges<UnitContext>());
            DbDatabase.SetInitializer(new UnitContextInitializer());
        }

        public DbSet<ItemBase> Options { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<Unit> Units { get; set; }
        public DbSet<Profile> Professionals { get; set; }

        #region Test
        //public DbSet<Person> Persons { get; set; }
        //public DbSet<Order> Orders { get; set; }
        #endregion

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // Converntions
            modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
            // Configurations
            modelBuilder.Configurations.Add(new ItemConfiguration());
            modelBuilder.Configurations.Add(new UserRoleConfiguration());
            modelBuilder.Configurations.Add(new UnitConfiguration());
            modelBuilder.Configurations.Add(new ProfileConfiguration());
            // WholeTransfer
            modelBuilder.Configurations.Add(new WholeTransferConfiguration());

            #region Test
            //modelBuilder.ComplexType<Address>();
            //modelBuilder.Entity<Order>()
            //    .HasRequired(o => o.Person)
            //    .WithMany(p => p.Orders)
            //    .IsIndependent()
            //    .Map(m => m.MapKey(p => p.PersonId, "CustomFkToPersonId"));
            #endregion
        }

        private class UnitContextInitializer : IDatabaseInitializer<UnitContext>
        {
            public void InitializeDatabase(UnitContext context)
            {
                if (!context.Database.Exists() || !context.Database.CompatibleWithModel(false))
                {
                    context.Database.CreateIfNotExists();
                    ((IObjectContextAdapter)context).ObjectContext
                        .ExecuteStoreCommand(@"ALTER TABLE [ItemCodes] ADD CONSTRAINT [DF__IsValid] DEFAULT (1) FOR [IsValid]");

                    ((IObjectContextAdapter)context).ObjectContext
                        .ExecuteStoreCommand(@"ALTER TABLE [Users] ADD CONSTRAINT [DF__IsValid] DEFAULT (1) FOR [IsValid]");
                }
            }
        }
    }

    public class ItemConfiguration : EntityTypeConfiguration<ItemBase>
    {
        public ItemConfiguration()
        {
            ToTable("ItemCodes");
            Property(u => u.Name).IsRequired().HasMaxLength(200);
            Property(u => u.Description).HasMaxLength(200);
            Property(u => u.Type).HasMaxLength(20); 
            
            HasKey(u => u.Code).Property(u => u.Code).HasDatabaseGenerationOption(DatabaseGenerationOption.Identity);
        }
    }

    public class UserRoleConfiguration : EntityTypeConfiguration<User>
    {
        public UserRoleConfiguration()
        {
            HasKey(u => u.Id);
            Property(u => u.Name).HasMaxLength(100);
            Property(u => u.EncryptPwd).HasMaxLength(50);
        }
    }

    public class ProfileConfiguration : EntityTypeConfiguration<Profile>
    {
        public ProfileConfiguration()
        {
            HasKey(p => p.UserId);
            Property(p => p.Name).HasMaxLength(20);
            Property(p => p.Gender).HasMaxLength(10);
            Property(p => p.Nationality).HasMaxLength(100);
            Property(p => p.NativePlace).HasMaxLength(100);
            Property(p => p.Separation).HasMaxLength(10);
            Property(p => p.College).HasMaxLength(100);
            Property(p => p.Major).HasMaxLength(100);
            Property(p => p.HomeTown).HasMaxLength(100);
            Property(p => p.ProfPos).HasMaxLength(100);
            Property(p => p.ProfTitle).HasMaxLength(100);
            Property(p => p.WorkKind).HasMaxLength(50);
            Property(p => p.SalaryGrade).HasMaxLength(50);
            Property(p => p.Family).HasMaxLength(100);
            Property(p => p.Remark1).HasMaxLength(200);
            Property(p => p.Remark2).HasMaxLength(200);
            //
            Property(p => p.OriginalIn).HasMaxLength(100);
            Property(p => p.OriginalOut).HasMaxLength(100);
            Property(p => p.OriginalInUpUnit).HasMaxLength(100);
            Property(p => p.OriginalOutUpUnit).HasMaxLength(100);
            Property(p => p.OriginalInUnitKind).HasMaxLength(50);
            Property(p => p.OriginalOutUnitKind).HasMaxLength(50);
            Property(p => p.OriginalInUnitType).HasMaxLength(50);
            Property(p => p.OriginalOutUnitType).HasMaxLength(50);
            //
            Property(p => p.ApprovalDate).IsOptional();
            Property(p => p.ModifiedDate).IsOptional();
            Property(p => p.MarriedDate).IsOptional();
            Property(p => p.WorkStart).IsOptional();
            Property(p => p.BirthDate).IsOptional();
            Property(p => p.PrintDate).IsOptional();
         }
    }

    public class UnitConfiguration : EntityTypeConfiguration<Unit>
    {
        public UnitConfiguration()
        {        
            Property(u => u.Name).HasMaxLength(200);
            Property(u => u.Description).HasMaxLength(200);
            Property(u => u.Address).HasMaxLength(200);
            Property(u => u.Contact).HasMaxLength(200);
            Property(u => u.ContactTel).HasMaxLength(100);
            
            HasKey(u => u.Id).Property(u => u.Id).HasDatabaseGenerationOption(DatabaseGenerationOption.Identity);
            // 单位区域
            HasOptional(u => u.UnitType);
            // 父子关系             
            HasOptional(u => u.ParentUnit)
                .WithMany(c => c.ChildUnits)
                .IsIndependent();
        }
    }

    public class WholeTransferConfiguration : EntityTypeConfiguration<WholeTransfer>
    {
        public WholeTransferConfiguration()
        {
            HasKey(u => u.Id);
            Property(u => u.InUnit).HasMaxLength(200);
            Property(u => u.OutUnit).HasMaxLength(200);
            Property(u => u.Description).HasMaxLength(200);
            Property(u => u.TransferFile).HasMaxLength(100);
            Property(u => u.ApprovalDate).IsOptional();
            // 父子关系 
            HasMany(u=>u.Profiles).WithOptional(p=>p.WholeTransfer);
        }
    }

}
